jQuery(document).ready(function() {
	
	selectFid();

	initTable();
	//$('#menuTable').bootstrapTable('hideColumn', 'menufid');
	
	App.setPage("menu");  //Set current page
	App.init(); //Initialise plugins and elements
	
	//列表查询事件
	$('#search').click(function(){
		$('#menuTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
	});
	
	
	//新增菜单
	$('#addMenu').click(function(){
		$('#title').html("菜单新增");
		$("#modalMenu").modal('show');
	});
	
	//批量删除
	$('#batchDelete').click(function(){
		var data = $('#menuTable').bootstrapTable('getSelections');
		if(data.length <= 0){
			window.wxc.xcConfirm('请勾选要<strong>批量删除</strong>的菜单数据', window.wxc.xcConfirm.typeEnum.info);
			return;
		}
		var menuids = "";
		var names = "";
		for(var i = 0; i < data.length; i++){
			menuids += data[i].menuid + ",";
			names += data[i].name + ",";
		}
		
		menuids = menuids.substring(0, menuids.length - 1);
		window.wxc.xcConfirm('是否<strong>批量删除</strong>菜单数据?<br /><span style="color:red;">['+ names +']</span>', window.wxc.xcConfirm.typeEnum.confirm,{
			onOk:function(v){
				$.ajax({ 
					url: projectPath + 'menu/batchDelete.do',
					data: {"menuids": menuids},
					dataType: "json",
					success: function(data){	            						
						if(data.result == 1){        	
							window.wxc.xcConfirm('删除菜单['+ data.datas[0].dictcode +']成功!', window.wxc.xcConfirm.typeEnum.info);
				        	$('#menuTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
						}
			      	}
				});
			}
		});
	});
	
	//保存数据事件
	$('#save').click(function(){
		//var a = $("#icon").find("option:selected").text().replace(/[ ]/g,"");
		var menuData = $("#menuForm").serializeObject();
		console.log(menuData);
		if(!check(menuData)){
			return true;
		};
		$.ajax({ 
			method: 'post',
			url: projectPath + 'menu/save.do',
			data: JSON.stringify(menuData),
			dataType: "json",
	        contentType: "application/json",
			success: function(data){	
		    	window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.info);
		    	if(data.result == 1){
		    		$('#menuTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
		    		$('#modalMenu').modal('hide');
		    	}
	      	}
		});
	});
	
	
	//清空表单数据事件
	$("#modalMenu").on("hidden.bs.modal", function() {

		$("#remark").val('');
		$(this).find('[type="text"]').val('');
		$(this).find('[type="radio"]').prop("checked",true);
		$('select').prop('selectedIndex', 0);
	});
	
});		

function initTable(){	
	$('#menuTable').bootstrapTable({
		method: 'post',
	    url: projectPath + 'menu/list.do',
	    pagination: true, //分页
	    dataType: "json",
        contentType: "application/json",
        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        striped: true,      //是否显示行间隔色
        sidePagination: "server",
        ////查询参数,每次调用是会带上这个参数，可自定义                         
        queryParams:function(params) {
            return {
                	pageNum: params.offset / params.limit + 1,
                	pageSize: params.limit,
                	name: $('#menuname').val(),
                	menufid: $('#menufidname').val()
                };
        },
	    columns: [{
            field : 'checked',
            checkbox : true

        }, {  
            field : 'number',  
            title : '序号',  
            align : 'center',
            width : '80px',
            formatter : function(value, row, index) { 
                var page = $('#menuTable').bootstrapTable("getPage");  
                return page.pageSize * (page.pageNumber - 1) + index + 1;  
            }  
        },{
        	field: 'menuid',
        	visible: false
        },{
	        field: 'name',
	        title: '菜单名称',
	    },{
	        field: 'menufid',
	        visible: false
	    },{
	        field: 'menufname',
	        title: '父级菜单',
	        formatter:function(value,row,index){
	        	if(value == null || value == ''){
	        		return '-';
	        	}
	        	return value;
	        }
	    },{
	        field: 'url',
	        title: '菜单URL'
	    },{
	        field: 'icon',
	        title: '图标'
	    }, {
	        field: 'ifenable',
	        title: '是否生效',
	        formatter:function(value,row,index){
	        	var result = value;
	        	
	        	if(value == "1")
	        		result = "是";
	        	else 							
        			result = "否";
	        	return result;
	        }
	    },{
            field: 'operate',
            title: '操作',
            align: 'center',
            width: '200px',
            events: operateEvents,
            formatter: operateFormatter
        } ]
	});
}

function operateFormatter(value, row, index) {
    return [
        '<button type="button" class="Edit btn btn-warning  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-edit"></span>编辑</button>',
        '<button type="button" class="Delete btn btn-danger  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span>删除</button>'
    ].join('');
}

window.operateEvents = {
    'click .Edit': function (e, value, row, index) {
		$('#title').html("菜单修改");
		$("#modalMenu").modal('show');
		$("#menuid").val(row.menuid);
		$("#name").val(row.name);
		$("#url").val(row.url);
		$("#remark").val(row.remark);
		$('[name="ifenable"][value=' + row.ifenable + ']').prop("checked",true);
		$('#selectfid').val(row.menufid);
		$('#icon').val(row.icon);
    },
    'click .Delete': function (e, value, row, index) {
    	
		var menuid = row.menuid;
		var name = row.name;
		window.wxc.xcConfirm('是否<strong>删除</strong>菜单数据?<br /><span style="color:red;">['+ name +']</span>', window.wxc.xcConfirm.typeEnum.confirm,{
			onOk:function(v){
				$.ajax({ 
					url: projectPath + 'menu/delete.do',
					data: {"menuid": menuid},//data: {"menucode": menucode},
					dataType: "json",
					success: function(data){	            						
						if(data.result == 1){
				        	$('#menuTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
						}
			      	}
				});
			}
		});
    }
 };

//菜单新增父级菜单下拉选
function selectFid(){
	$.ajax({ 
		method: 'get',
		url: projectPath + 'menu/selectFid.do',
		dataType: "json",
        contentType: "application/json",
		success: function(data){
			// 先清空控件数据
			$('#selectfid').empty();
			$('#icon').empty();
			
			var option1 = $("<option>").val("").text("");
			var option2 = $("<option>").val("").text("");
			$('#selectfid').append(option1);
			$('#icon').append(option2);
			$.each(data.rows, function(index, item) {
	            $("#selectfid").append('<option value="'+item.menuid+'">' + item.name+ '</option>');
	            $("#menufidname").append('<option value="'+item.menuid+'">' + item.name+ '</option>');
				$("#icon").append('<option value="'+item.icon+'">' + item.icon+ '</option>');
	        });

		}
	});
}
//selectFidOne
function selectFidOne(name){
	var ret;
	$.ajax({ 
		url: projectPath + 'menu/selectFidOne.do',
		data: {'name':name},
		dataType: "json",
		async:false,
		success: function(data){	

			ret = data.rows[0].menufid;
			
		}
	});
	return ret;

}

function check(data){	
	var result = true;
	
	var mustStr = "name";
	
	var strMsg = "";
	var mustStrs = mustStr.split(',');
	for(var i=0; i<mustStrs.length; i++){
		var obj = $('[name="'+mustStrs[i]+'"]');
		if(obj.val() == ""){
			strMsg += obj.attr("placeholder") + "！<br />";
			result = false;
		}
	}
	
	if($('#selectfid').val() != ''){
		if($('#url').val() == ''){
			strMsg += $('#url').attr("placeholder") + "！<br />";
			result = false;
		}
	}
	
	if(strMsg != ""){
		window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.error);
	}
	
	return result;
}
